<?php
namespace Manage\Controller;

/**
 * 基础商品库
 * Class GoodsController
 * @package Manage\Controller
 */
class GoodsController extends BaseController
{

    /**
     * 商品列表
     */
    public function index()
    {

        $where['a.disabled'] = 'false';
        // 名称
        if (isset($_GET['name']) && !empty($_GET['name'])) {
            $name = I('name');
            $where['a.name'] = ['like', "%$name%"];
            $this->assign('name', $name);
        }
        // 条码
        if (isset($_GET['barcode']) && !empty($_GET['barcode'])) {
            $barcode = I('barcode');
            $where['b.barcode'] = ['like', "%$barcode%"];
            $this->assign('barcode', $barcode);
        }

        $goods = M('b2c_goods a'); // 实例化User对象
        $count = $goods->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $goods
            ->join("left join " . C('DB_PREFIX') . "b2c_products b on a.goods_id = b.goods_id")
            ->where($where)
            ->order('a.goods_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->group('a.goods_id')
            ->select();

        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    /**
     * 添加商品
     */
    public function add()
    {

        if (IS_POST) {
            $cat_id = I('cat_id'); // 分类
            $name = I('name'); // 商品名称
            $name2 = I('name2'); // 商品副标题
            $weight = I('weight'); // 商品重量
            $unit = I('unit'); // 商品单位
            $highlight = I('highlight'); // 商品亮点
            $last_modify = I('last_modify'); // 时间
            $content = I('content'); // 内容

            $keywords = I('keywords'); // 商品属性名称
            $values = I('values'); // 商品属性值

            $spec_info = I('spec_info'); // 规格描述
            $mktprice = I('mktprice'); // 门店市场价
            $price = I('price'); // 门店销售价
            $store = I('store'); // 门店库存
            $bn = I('bn'); // 货号
            $barcode = I('barcode'); // 条码
            $images = I('images'); // 图片
            $image_num = I('input-num'); // 默认的图片id
            $is_qgs_show = I('is_qgs_show'); // 全国送显示

            foreach ($barcode as $k=>$v){
                $barcode[$k] = trim($v);
            }

            if (empty($spec_info[0]) || empty($mktprice[0]) || empty($price[0]) || empty($store[0]) || empty($bn[0])) {
                $this->error('请填写完全规格信息');
                exit;
            }

            try {
                M()->execute('begin');

                // 添加image图片
                if (is_array($images) && !empty($images)) {

                    for ($i = 0; $i < count($images); $i++) {
                        $image_data['url'] = $images[$i];

                        $images_thumb = explode("/", $images[$i]);

                        $l_url = '/' . $images_thumb[0] . '/' . 'l_' . $images_thumb[1];
                        $m_url = '/' . $images_thumb[0] . '/' . 'm_' . $images_thumb[1];
                        $s_url = '/' . $images_thumb[0] . '/' . 's_' . $images_thumb[1];

                        $image_data['l_url'] = $l_url;
                        $image_data['m_url'] = $m_url;
                        $image_data['s_url'] = $s_url;

                        $image_data['last_modified'] = time();
                        $image_data['image_id'] = md5(time() . $i);
                        $image_id = M('image_image')->add($image_data);
                        if ($image_id === false) {
                            throw new \Exception($i . 'image');
                        }

                        if ($i == $image_num) {
                            $target = $image_data['image_id'];
                        }
                        $image_id_array[] = $image_data['image_id'];
                    }
                }

                $goods_data['cat_id'] = $cat_id;
                $goods_data['name'] = $name;
                $goods_data['name2'] = $name2;
                $goods_data['weight'] = $weight;
                $goods_data['unit'] = $unit;
                $goods_data['highlight'] = $highlight;
                $goods_data['last_modify'] = strtotime($last_modify);
                $goods_data['intro'] = $content;

                if (is_array($keywords) && !empty($keywords)) {
                    for ($i = 0; $i < count($keywords); $i++) {
                        $arr[$keywords[$i]] = $values[$i];
                    }
                    $goods_property = json_encode($arr);
                    $goods_data['goods_property'] = $goods_property;
                }

                $goods_add = M('b2c_goods')->add($goods_data); // 添加商品信息
                if ($goods_add === false) {
                    throw new \Exception(1);
                }

                M('b2c_goods')->where(['goods_id' => $goods_add])->save(['image_default_id' => $target]);


                // 添加商品和图片关联表image_image_attach
                for ($j = 0; $j < count($image_id_array); $j++) {
                    $image_image_attach_data['target_id'] = $goods_add;
                    $image_image_attach_data['image_id'] = $image_id_array[$j];
                    $image_image_attach_data['target_type'] = 'goods';
                    $image_image_attach_data['last_modified'] = time();
                    $image_image_attach_add = M('image_image_attach')->add($image_image_attach_data);
                    if ($image_image_attach_add === false) {
                        throw new \Exception($j . 'attach');
                    }
                }

                // 添加货品信息
                if (is_array($spec_info) && !empty($spec_info)) {
                    for ($i = 0; $i < count($spec_info); $i++) {
                        $products_data['name'] = $name;
                        $products_data['spec_info'] = $spec_info[$i];
                        $products_data['mktprice'] = $mktprice[$i];
                        $products_data['price'] = $price[$i];
                        $products_data['store'] = $store[$i];
                        $products_data['bn'] = $bn[$i];
                        $products_data['barcode'] = $barcode[$i];
                        $products_data['goods_id'] = $goods_add;
                        $products_data['disabled'] = 'false';
                        $products_data['is_qgs_show'] = $is_qgs_show[$i];
                        $products = M('b2c_products')->add($products_data);
//echo M('b2c_products')->_sql();exit;
                        if ($products === false) {
                            throw new \Exception($i . 'spec');
                        }
                    }
                } else {

                    $products_data['goods_id'] = $goods_add;
                    $products = M('b2c_products')->add($products_data);
                    if ($products === false) {
                        throw new \Exception('spec');
                    }
                }

                M()->execute('commit');
                $this->success('添加商品成功', U('Goods/index'));
            } catch (\Exception $e) {
                M()->execute('rollback');
                $this->error('错误代码' . $e->getMessage());
            }

        } else {
            // 商品分类
            $goods_cat = M('b2c_goods_cat');
            $parent_list = $goods_cat->where(['parent_id' => '0'])->select();
            $second_list = $goods_cat->where(['parent_id' => ['NEQ', '0']])->select();
            $this->assign('parent_list', $parent_list);
            $this->assign('second_list', $second_list);
            $this->display();
        }
    }

    /**
     * 修改商品
     */
    public function update()
    {
        $goods_id = I('goods_id');

        $goods = M('b2c_goods');

        // 商品信息
        $goods_msg = $goods->where(['goods_id' => $goods_id, 'disabled' => 'false'])->find();

        // 图片
        $images = M('image_image_attach a')->join('left join sdb_image_image b on a.image_id = b.image_id')
            ->where(['a.target_id' => $goods_id, 'a.target_type' => 'goods'])
            ->select();
//        echo M('image_image_attach a')->_sql();
//        var_dump($images);

        // 分类
        $goods_cat = M('b2c_goods_cat');
        $parent_list = $goods_cat->where(['parent_id' => '0'])->select();
        $second_list = $goods_cat->where(['parent_id' => ['NEQ', '0']])->select();

        // 商品属性
        $goods_property = json_decode($goods_msg['goods_property'], true);

        // 货品
        $product = M('b2c_products')->where(['goods_id' => $goods_id, 'disabled' => 'false'])->select();
//var_dump($product);exit;
        $this->assign('parent_list', $parent_list);
        $this->assign('second_list', $second_list);
        $this->assign('goods_msg', $goods_msg);
        $this->assign('images', $images);
        $this->assign('goods_property', $goods_property);
        $this->assign('product', $product);

        $this->display();
    }

    /**
     * 修改保存
     */
    public function save()
    {
        if (IS_POST) {
            $goods_id = I('goods_id');

            $goods = M('b2c_goods');

            // 商品信息
            $goods_msg = $goods->where(['goods_id' => $goods_id])->find();

            if (empty($goods_msg)) {
                $this->error('错误的商品');
            }

            $cat_id = I('cat_id'); // 分类
            $name = I('name'); // 商品名称
            $name2 = I('name2'); // 商品副标题
            $weight = I('weight'); // 商品重量
            $unit = I('unit'); // 商品单位
            $highlight = I('highlight'); // 商品亮点
            $last_modify = I('last_modify'); // 时间
            $content = I('content'); // 内容

            $keywords = I('keywords'); // 商品属性名称
            $values = I('values'); // 商品属性值

            $spec_info = I('spec_info'); // 规格描述
            $mktprice = I('mktprice'); // 门店市场价
            $price = I('price'); // 门店销售价
            $store = I('store'); // 门店库存
            $bn = I('bn'); // 货号
            $barcode = I('barcode'); // 条码
            $images = I('images'); // 图片
            $image_num = I('input-num'); // 默认的图片id
            $product_id = I('product_id'); // 货品id

            $is_qgs_show = I('is_qgs_show'); // 全国送显示

            if (empty($spec_info[0]) || empty($mktprice[0]) || empty($price[0]) || empty($store[0]) || empty($bn[0])) {
                $this->error('请填写完全规格信息');
                exit;
            }

            try {
                M()->execute('begin');

                /*                // 删除图片
                                $delete_images = M('image_image')->where(['goods_id' => $goods_id])->delete();
                                if ($delete_images === false) {
                                    throw new \Exception('images delete error');
                                }
                                // 删除图片商品管理id
                                $image_image_attach_delete = M('image_image_attach')->where(['target_id' => $goods_id, 'target_type' => 'goods'])->delete();
                                if ($image_image_attach_delete === false) {
                                    throw new \Exception('image_image_attach delete error');
                                }*/

                // 删除图片商品管理id
                $delete_images = M()->execute("DELETE p.*, pp.* FROM sdb_image_image p, sdb_image_image_attach pp WHERE	p.image_id = pp.image_id AND pp.target_id = $goods_id AND pp.target_type = 'goods'");
                if ($delete_images === false) {
                    throw new \Exception('images delete error');
                }

                // 添加image图片
                if (is_array($images) && !empty($images)) {

                    $target = 0;
                    for ($i = 0; $i < count($images); $i++) {
                        $image_data['url'] = $images[$i];

                        // 判断如果商品地址类型是2.0的地址就这样处理
                        if (strstr($images[$i], 'public/images/')) {
                            $l_url = $images[$i];
                            $m_url = $images[$i];
                            $s_url = $images[$i];
                        } else { // 如果是3.0新上的图片，从新组合图片链接
                            $images_thumb = explode("/", $images[$i]);
                            $l_url = '/' . $images_thumb[0] . '/' . 'l_' . $images_thumb[1];
                            $m_url = '/' . $images_thumb[0] . '/' . 'm_' . $images_thumb[1];
                            $s_url = '/' . $images_thumb[0] . '/' . 's_' . $images_thumb[1];
                        }

                        // 保存图片链接到图片表
                        $image_data['l_url'] = $l_url;
                        $image_data['m_url'] = $m_url;
                        $image_data['s_url'] = $s_url;
                        $image_data['last_modified'] = time();
                        $image_data['image_id'] = md5(time() . $i);

                        $image_id = M('image_image')->add($image_data);
                        if ($image_id === false) {
                            throw new \Exception($i . 'image');
                        }

                        if ($i == $image_num) {
                            $target = $image_data['image_id'];
                        }
                        $image_id_array[] = $image_data['image_id'];
                    }
                }

                $goods_data['cat_id'] = $cat_id;
                $goods_data['name'] = $name;
                $goods_data['name2'] = $name2;
                $goods_data['weight'] = $weight;
                $goods_data['unit'] = $unit;
                $goods_data['highlight'] = $highlight;
                $goods_data['last_modify'] = strtotime($last_modify);
                $goods_data['intro'] = $content;
                $goods_data['image_default_id'] = $target;  // 添加默认图片


                if (is_array($keywords) && !empty($keywords)) {
                    for ($i = 0; $i < count($keywords); $i++) {
                        $arr[$keywords[$i]] = $values[$i];
                    }
                    $goods_property = json_encode($arr);
                    $goods_data['goods_property'] = $goods_property;
                }

                $goods_save = M('b2c_goods')->where(['goods_id' => $goods_id])->save($goods_data); // 修改商品信息
                if ($goods_save === false) {
                    throw new \Exception(1);
                }

                // 添加商品和图片关联表image_image_attach
                for ($j = 0; $j < count($image_id_array); $j++) {
                    $image_image_attach_data['target_id'] = $goods_id;
                    $image_image_attach_data['image_id'] = $image_id_array[$j];
                    $image_image_attach_data['target_type'] = 'goods';
                    $image_image_attach_data['last_modified'] = time();
                    $image_image_attach_add = M('image_image_attach')->add($image_image_attach_data);
                    if ($image_image_attach_add === false) {
                        throw new \Exception($j . 'attach');
                    }
                }

                // 添加货品信息
                if (is_array($spec_info) && !empty($spec_info)) {
                    for ($i = 0; $i < count($spec_info); $i++) {
                        $products_data['name'] = $name;
                        $products_data['spec_info'] = $spec_info[$i];
                        $products_data['mktprice'] = $mktprice[$i];
                        $products_data['price'] = $price[$i];
                        $products_data['store'] = $store[$i];
                        $products_data['bn'] = $bn[$i];
                        $products_data['barcode'] = $barcode[$i];
                        $products_data['goods_id'] = $goods_id;
                        $products_data['disabled'] = 'false';

                        $product_id_item = $product_id[$i];

                        if ($product_id_item) {
                            // 修改货品
                            $products_data['is_qgs_show'] = $is_qgs_show[$product_id_item];

                            $products = M('b2c_products')->where(['product_id' => $product_id_item])->save($products_data);

                            if ($products === false) {
                                throw new \Exception($i . '：货品修改失败');
                            }
                        }
                    }
                }

                // 新增货品
                $is_qgs_show_update = I('is_qgs_show_update');
                if (is_array($is_qgs_show_update)) {

                    for ($j = 0; $j < count($is_qgs_show_update); $j++) {

                        $spec_info_qgs = I('spec_info_qgs'); // 规格描述
                        $mktprice_qgs = I('mktprice_qgs'); // 门店市场价
                        $price_qgs = I('price_qgs'); // 门店销售价
                        $store_qgs = I('store_qgs'); // 门店库存
                        $bn_qgs = I('bn_qgs'); // 货号
                        $barcode_qgs = I('barcode_qgs'); // 条码

                        $products_data['name'] = $name;
                        $products_data['spec_info'] = $spec_info_qgs[$j];
                        $products_data['mktprice'] = $mktprice_qgs[$j];
                        $products_data['price'] = $price_qgs[$j];
                        $products_data['store'] = $store_qgs[$j];
                        $products_data['bn'] = $bn_qgs[$j];
                        $products_data['barcode'] = $barcode_qgs[$j];
                        $products_data['goods_id'] = $goods_id;
                        $products_data['disabled'] = 'false';

                        $products_data['is_qgs_show'] = $is_qgs_show_update[$j + 1];
                        $products = M('b2c_products')->add($products_data);

                        if ($products === false) {
                            throw new \Exception($j . '：增加失败');
                        }
                    }
                }


                M()->execute('commit');
                $this->success('成功');
            } catch (\Exception $e) {
                M()->execute('rollback');
                $this->error('错误代码：' . $e->getMessage());
            }
        } else {
            $this->error('错误的商品');
        }

    }

    /**
     * 删除货品
     */
    public function del_product()
    {
        $product_id = I('product_id');
        // 删除货品判断改货品是否有店铺在使用中，如果在就不能删除
        $store_product = M('b2c_store_product')->field('local_id')->where(['store_status' => 'true', 'product_id' => $product_id])->select();

        $arr_store = [];
        if ($store_product) {
            for ($i = 0; $i < count($store_product); $i++) {
                // 查询门店信息
                $store = M('webpos_local_store')->where(['local_id' => $store_product[$i]['local_id']])->find();
                if ($store) {
                    $arr_store[] = $store['local_name'];
                }
            }
            echo json_encode(['status' => 'false', 'store' => $arr_store]);
        } else {

            // 删除货品
            $dekete_products = M('b2c_products')->where(['product_id' => $product_id])->save(['disabled' => 'true']);

            if ($dekete_products) {
                echo json_encode(['status' => 'true', 'store' => '']);
            } else {
                echo json_encode(['status' => 'false', 'store' => '']);
            }
        }
    }

    /**
     * 删除商品
     */
    public function delete()
    {
        $goods_id = I('goods_id');

        $product = M('b2c_products')->where(['goods_id' => $goods_id, 'disabled' => 'false'])->select();

        if ($product) {
            $this->error('请先删除货品');
        } else {
            $delete_goods = M('b2c_goods')->where(['goods_id' => $goods_id])->save(['disabled' => 'true']);

            if ($delete_goods) {
                $this->success('删除成功', '/Manage/Goods/index');
            } else {
                $this->error('删除失败');
            }
        }
    }

    /**
     * 商品条形码查询
     */
    public function select_barcode()
    {
        $b2c_products = M("b2c_products");
        $barcode = I("barcode");
        $flag = 0;
        if (!empty($barcode)) {
            $product = $b2c_products->where(['barcode' => $barcode])->find();
            if (!empty($product['product_id'])) {
                $flag = 1;
            }
        }
        echo $flag;
    }

}